package com.zhoug.player3.hik;

import android.graphics.Rect;
import android.text.TextUtils;
import android.view.TextureView;


import com.hikvision.hatomplayer.DefaultHatomPlayer;
import com.hikvision.hatomplayer.HatomPlayer;
import com.hikvision.hatomplayer.PlayCallback;
import com.hikvision.hatomplayer.PlayConfig;
import com.hikvision.hatomplayer.core.Quality;
import com.zhoug.common3.Logger;
import com.zhoug.player3.core.BasePlayer;
import com.zhoug.player3.core.PlayError;
import com.zhoug.player3.core.ZPlayer;

import java.util.Objects;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * 海康播放sdk封装
 *
 * @Author: zhoug
 * @Date: 2023/8/29
 * @Description:
 */
public class HikPlayerHelper extends BasePlayer {
    private static final String TAG = ">>>HikPlayerHelper";
    private static boolean DEBUG = true;
    private boolean isRecording;//是否正在录像
    private HatomPlayer mPlayer;
    private HikTalkHelper mHikTalkHelper;
    private PlayConfig mPlayConfig;

    public HikPlayerHelper() {
    }

    public HikPlayerHelper(PlayConfig playConfig) {
        this.mPlayConfig = playConfig;
    }


    /**
     * 设置显示页面
     *
     * @param textureView
     */
    @Override
    public void setVideoTextureView(@Nullable TextureView textureView) {
        super.setVideoTextureView(textureView);
        _setTextureView();
    }


    private void _setTextureView() {
        if (mPlayer != null) {
            if (mTextureView != null && mTextureView.getSurfaceTexture() != null) {
                mTextureView.setKeepScreenOn(true);
                mPlayer.setSurfaceTexture(mTextureView.getSurfaceTexture());
            }
        }

    }

    /**
     * 始化播放器
     */
    protected synchronized void initPlayer() {
        if (mPlayer != null) {
            Logger.d(TAG, "initPlayer:无需重复初始化播放器");
            return;
        }
        mPlayer = new DefaultHatomPlayer();
        if (mPlayConfig == null) {
            mPlayConfig = new PlayConfig();
            //使用硬解码
            mPlayConfig.hardDecode = true;
            //开启智能信息
            mPlayConfig.privateData = true;
        }
        //设置播放参数
        mPlayer.setPlayConfig(mPlayConfig);
        //设置播放回掉
        mPlayer.setPlayStatusCallback(mPlayStatusCallback);
      /*  mPlayer.setRecordCallback(new PlayCallback.RecordCallback() {
            @Override
            public void recordTime(int time) {
                Logger.d(TAG, "recordTime:" + time);
            }
        });*/
        //realPlayUrl为预览短链接，需要通过调用openApi获取
//        mPlayer.setDataSource(realPlayUrl,null);
        _setTextureView();

    }

    /**
     * 播放回掉
     */
    private final PlayCallback.PlayStatusCallback mPlayStatusCallback = new PlayCallback.PlayStatusCallback() {
        @Override
        public void onPlayerStatus(@NonNull PlayCallback.Status status, String errorCode) {
            //status 共三种状态：SUCCESS（播放成功）、FAILED（播放失败）、EXCEPTION（取流异常）
            //错误码，只有 FAILED 和 EXCEPTION 才有值
            //注意：回调仍为子线程
            String errorMsg = null;
            int code = PlayError.UNKNOWN_ERROR;
            if (!TextUtils.isEmpty(errorCode)) {
                errorCode = HikErrors.errorCodeToHexString(errorCode);
                errorMsg = HikErrors.getErrorMsg(errorCode);
                if (Objects.equals(HikErrors.URL_EXPIRE, errorCode)) {
                    code = PlayError.URL_EXPIRE;
                }
            }
            switch (status) {
                case SUCCESS:
                    if (DEBUG) {
                        Logger.d(TAG, "onPlayerStatus:播放成功");
                    }
                    callStatusChange(STATE_PLAYING);
                    break;
                case FAILED:
                    Logger.e(TAG, "onPlayerStatus:播放失败:" + errorMsg);
                    stopPlay();
                    callError(code, errorMsg);
                    break;
                case FINISH:
                    callStatusChange(STATE_ENDED);
                    if (DEBUG) {
                        Logger.d(TAG, "onPlayerStatus:播放完成");
                    }
                    stopPlay();
                    break;
                case EXCEPTION:
                    Logger.e(TAG, "onPlayerStatus:取流异常:" + errorMsg);
                    stopPlay();
                    callError(PlayError.IO_EXCEPTION, errorMsg);
                    break;
            }
        }
    };

    private void _start() {
        if (mPlayer != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        if (mPlayer != null) {
                            mPlayer.start();
                        }
                    }
                }
            }).start();
        }
    }


    private void _stop() {
        if (mPlayer != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        if (mPlayer != null) {
                            mPlayer.stop();
                        }
                    }
                }
            }).start();
        }
    }

    private void _resume() {
        if (mPlayer != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        if (mPlayer != null) {
                            mPlayer.resume();
                        }
                    }
                }
            }).start();
        }
    }

    private void _pause() {
        if (mPlayer != null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    synchronized (this) {
                        if (mPlayer != null) {
                            mPlayer.pause();
                        }
                    }
                }
            }).start();
        }
    }


    private void _setMute(boolean mute) {
        if (mPlayer != null) {
            mPlayer.enableAudio(!mute);
        }
    }

    private void _changeStream(Quality quality) {
        if (mPlayer != null) {
            int code = mPlayer.changeStream(quality);
            if (code != 0) {
                callError(code, "切换码流失败");
            }
        }
    }


    /**
     * 开始播放,每次都是重新加载资源播放,可以播放新的url
     */
    @Override
    public void startPlay() {
        if (TextUtils.isEmpty(mPlayUrl)) {
            callError(PlayError.URL_IS_EMPTY, "playUrl为空");
            return;
        }
        if (mPlayer == null) {
            initPlayer();
            if (mPlayer == null) {
                callError(PlayError.PLAYER_INIT_FAILURE, "初始化播放器失败");
                return;
            }
        } else {
            int playSate = getPlaySate();
            if (playSate != ZPlayer.STATE_IDLE) {
                _stop();
            }
        }
        mPlayer.setDataSource(mPlayUrl, null);
        callStatusChange(ZPlayer.STATE_START);
        _start();
    }


    /**
     * 停止播放,会释放加载的媒体和资源
     */
    @Override
    public void stopPlay() {
        int playSate = getPlaySate();
        if (playSate != ZPlayer.STATE_IDLE) {
            _stop();
        }
        callStatusChange(ZPlayer.STATE_IDLE);
    }

    /**
     * 如果正在播放则暂停播放,否则调用{@link #stopPlay()}停止播放
     */
    @Override
    public void pausePlay() {
        int playSate = getPlaySate();
        if (playSate == ZPlayer.STATE_PLAYING) {
            _pause();
            callStatusChange(ZPlayer.STATE_PAUSE);
        } else {
            stopPlay();
        }
    }

    /**
     * 如果暂停了或者资源已经准备好了则播放,否则{@link #startPlay()}重新开始播放
     */
    @Override
    public void resumePlay() {
        int playSate = getPlaySate();
        if (playSate == ZPlayer.STATE_PAUSE) {
            _resume();
            callStatusChange(ZPlayer.STATE_PLAYING);
        } else {
            startPlay();
        }

    }


    /**
     * 设置静音
     *
     * @param mute true:静音,false:非静音
     */
    @Override
    public void setMute(boolean mute) {
        super.setMute(mute);
        _setMute(mute);
    }


    /**
     * 设置指定位置播放
     *
     * @param positionMs 毫秒
     */
    @Override
    public void seekTo(long positionMs) {

    }

    /**
     * 切换为直播
     */
    @Override
    public void switchToLive() {

    }

    @Override
    public long getCurrentTime() {
        if (mPlayer != null) {
            return mPlayer.getPlayedTime();
        }
        return super.getCurrentTime();
    }

    /**
     * 开始录制视频
     *
     * @param path 保存的视频地址,不一定使用
     */
    @Override
    public void startRecordVideo(String path) {
        if (mPlayer != null) {
            if (isPlaying()) {
                int success = mPlayer.startRecord(path);
                if (success == 0) {
                    isRecording = true;
                    callRecordVideoStart();
                } else {
                    isRecording = false;
                    callRecordVideoError(HikErrors.getErrorMsg(success));
                }
            }
        }
    }

    /**
     * 停止录制视频
     */
    @Override
    public void stopRecordVideo() {
        if (mPlayer != null && isRecording) {
            mPlayer.stopRecord();
        }
    }


    /**
     * 开启对讲
     */
    @Override
    public void startVoiceTalk() {
        if (mHikTalkHelper == null) {
            mHikTalkHelper = new HikTalkHelper();
        }
        if (mHikTalkHelper.isTalking()) {
            return;
        }
//        mHikTalkHelper.setPlayer(mPlayer);
        mHikTalkHelper.setOnTalkListener(mOnTalkListener);
        mHikTalkHelper.setTalkUrl(mTalkUrl);
        mHikTalkHelper.startVoiceTalk();


    }

    /**
     * 是否正在对讲
     *
     * @return
     */
    @Override
    public boolean isTalking() {
        return mHikTalkHelper != null && mHikTalkHelper.isTalking();
    }

    /**
     * 停止对讲
     */
    @Override
    public void stopVoiceTalk() {
        if (mHikTalkHelper != null) {
            mHikTalkHelper.stopVoiceTalk();
        }
    }


    @Override
    public void release() {
        super.release();
        if (mPlayer != null) {
            stopPlay();
        }
    }

    /**
     * 开启电子放大
     *
     * @param oRect
     * @param curRect
     */
    @Override
    public void openDigitalZoom(Rect oRect, Rect curRect) {
        if (mPlayer != null) {
            mPlayer.openDigitalZoom(oRect, curRect);
        }
    }

    /**
     * 关闭电子放大
     */
    @Override
    public void closeDigitalZoom() {
        if (mPlayer != null) {
            mPlayer.closeDigitalZoom();
        }
    }

}
